package com.ch.clinking.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentResultListener;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.DoCallBack;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.activity.AddMerActivity;
import com.ch.clinking.activity.EditMerStockActivity;
import com.ch.clinking.activity.MainActivity;
import com.ch.clinking.adapter.MerEditAdapter;
import com.ch.clinking.adapter.MerListAdapter;
import com.ch.clinking.adapter.MerListViewAdapter;
import com.ch.clinking.adapter.SearchListAdapter;
import com.ch.clinking.bean.Merchandise;
import com.ch.clinking.bean.MerchandiseDto;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MerFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    FragmentManager fragmentManager;

    private ProgressBar merFragmentLoadingProgressBar;

    private boolean flashFlag = true;

    private SwipeRefreshLayout swipeRefreshLayout;


    private Button billTemporaryFragmentAddButton;
    private TextView merCount;
    private ListView merListView;
    private AutoCompleteTextView autoCompleteTextView;
    private ScrollView scrollView;
    private LinearLayout linearListView;
    public Spinner changeShopSpinner;
    private RecyclerView recyclerViewMerList;
    private Button changeShop;

    private ClinkingApplication app;
    private List<MerchandiseDto> merchandiseDotList;
    private MerListAdapter merListAdapter;

    private ProgressBar progressBar;

    private MerchandiseDto merchandiseUpdateStock;

    private MerListViewAdapter merListViewAdapter;

    private ActivityResultLauncher<Intent> resultLauncher;

    public void setResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
    }

    public MerFragment() {
    }

    public static MerFragment newInstance(String param1, String param2) {
        MerFragment fragment = new MerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentManager = getParentFragmentManager();


        app = ClinkingApplication.getInstance();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("flashFlag", "1111111");

//        refreshMerchandiseList();
//        flashFlag = false;

    }


    public void refreshMerchandiseList() {
        showLoading();

        HashMap<String, String> selectMerchandiseList = new HashMap<>();
        selectMerchandiseList.put("shopId", app.shopList.get(app.shopPosition).getShopId());

        // 检查当前店铺，并更新下拉框显示的店铺名称
//        changeShopSpinner.setSelection(app.shopPosition);


        OkHttpUtil.getInstance().doPostForm("/mer/selectMerByShopId", new DoCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.d("MerListAdapter", "result:" + result);

                MerchandiseDto[] merchandiseArray = new Gson().fromJson(result, MerchandiseDto[].class);
                merchandiseDotList = Arrays.asList(merchandiseArray);


                Log.d("MerListAdapter", "refreshMerchandiseList");

                recyclerViewMerList.setLayoutManager(new LinearLayoutManager(getContext()));
                merListViewAdapter = new MerListViewAdapter(getActivity(), merchandiseDotList, progressBar);
                merListViewAdapter.setResultLauncher(resultLauncher);
                recyclerViewMerList.setAdapter(merListViewAdapter);

//                merListAdapter = new MerListAdapter(getContext(), R.layout.list_spu_layout, merchandiseList, getParentFragmentManager());
//                merListView.setAdapter(merListAdapter);
                merCount.setText(String.valueOf(merchandiseArray.length));

                // 设置搜索列表内容和适配器
                // 创建适配器
                SearchListAdapter searchAdapter = new SearchListAdapter(getContext(), R.layout.list_spu_layout, merchandiseDotList);
                autoCompleteTextView.setAdapter(searchAdapter);
                autoCompleteTextView.setThreshold(1);

                hideLoading();
                // 数据加载完成，发送广播
                Intent intent = new Intent("com.example.DATA_LOADED");
                LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);

            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(MerFragment.this.getActivity(), "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, selectMerchandiseList);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mer, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        billTemporaryFragmentAddButton = view.findViewById(R.id.billTemporaryFragmentAddButton);

        merCount = view.findViewById(R.id.totalSKCOfCount);
//        merListView = view.findViewById(R.id.fragment_mer_list);

        autoCompleteTextView = view.findViewById(R.id.autoCompleteTextView);
        scrollView = view.findViewById(R.id.scrollView);
        linearListView = view.findViewById(R.id.linearListView);

//        changeShop = view.findViewById(R.id.changeShop);
        changeShopSpinner = view.findViewById(R.id.changeShopSpinner);


        progressBar = view.findViewById(R.id.merFragmentLoadingProgressBar);

        recyclerViewMerList = view.findViewById(R.id.fragment_mer_list);

        swipeRefreshLayout = view.findViewById(R.id.merFragmentSwipeRefreshLayout);

        getParentFragmentManager().setFragmentResultListener("requestKey", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
                // 获取传递的数据
                String skc = result.getString("updatedMerchandise");
                updateListWithNewData(skc);
            }
        });

        // 初始化下拉框数据
        List<String> spinnerData = new ArrayList<>();
        for (int i = 0; i < app.shopList.size(); i++) {
            spinnerData.add(app.shopList.get(i).getShopName());
        }

        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, spinnerData);

        // 设置下拉框样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // 设置适配器
        changeShopSpinner.setAdapter(adapter);

        // 创建页面时加载数据
//        refreshMerchandiseList();


        // 设置下拉框点击事件
        changeShopSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                // 处理下拉框item点击事件
                String selectedItem = (String) parentView.getItemAtPosition(position);
                app.shopPosition = position;
                Log.d("shopPosition", String.valueOf(app.shopPosition));
                Log.d("flashFlag", String.valueOf(flashFlag));
                MainActivity activity = (MainActivity) requireActivity();

                if (!activity.flash) {
                    activity.refreshOrderList();
                } else {
                    activity.flash = false;
                }

//                merchandiseList.clear();
//                onResume();
//                if (flashFlag) {
                refreshMerchandiseList();
//                }
//                flashFlag = true;
//                Toast.makeText(getContext(), "Selected: " + selectedItem, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // 未选择任何item时的处理
            }
        });


        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });


//        merListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
//                builder.setTitle("确认删除");
//                builder.setMessage("确定删除<"+ merListAdapter.getItem(i).getTitle() +">吗?");
//                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        HashMap<String, String> merMap = new HashMap<>();
//                        merMap.put("skc",merListAdapter.getItem(i).getSkcId());
//                        // 执行删除操作，例如从数据集中移除对应项
//                        OkHttpUtil.getInstance().doPostForm("/mer/delete", new DoCallBack() {
//                            @Override
//                            public void onSuccess(String result) {
//                                Log.d("Mer Delete", result);
////                            remove(getItem(position));
//                                onResume();
//                                dialog.dismiss();
////                            merchandiseList.remove(position);
////                            merListAdapter.notifyDataSetChanged();
////                                merchandiseList.remove(position);
////                                List<Merchandise> update = new ArrayList<>();
////                                update.addAll(merchandiseList);
////                                update.remove(position);
////                                merchandiseList = update;
////                            notifyDataSetChanged();
//                            }
//
//                            @Override
//                            public void onError(Exception e) {
//                                Log.d("tag", "Mer Delete error");
//                                Toast.makeText(getContext(), "网络错误,请稍后再试", Toast.LENGTH_SHORT).show();
//                            }
//                        }, merMap);
//                    }
//                });
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int i) {
//                        dialog.dismiss();
//                    }
//                });
//                builder.show();
//                return false;
//            }
//        });

        initEvent();
    }

    // 按钮点击事件
    public void showDropdown(View view) {
        // 显示下拉框
        changeShopSpinner.performClick();
    }

    public void updateListWithNewData(String skc) {

        showLoading();

        // 在这里实现更新列表数据的逻辑

        // 获取订单TAG列表
        HashMap<String, String> mer = new HashMap<>();
        mer.put("skcId", skc);

        OkHttpUtil.getInstance().doPostForm("/mer/selectMerHaveOrderBySkcId", new DoCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(String result) {
                Log.d("selectMerDtoBySkcId", "result:"+result);

                merchandiseUpdateStock = new Gson().fromJson(result, MerchandiseDto.class);
                merListViewAdapter.updateMerStock(merchandiseUpdateStock);

                hideLoading();
            }

            @Override
            public void onError(Exception e) {
                Toast.makeText(getActivity(), "网络错误,获取商品失败,请稍后再试", Toast.LENGTH_SHORT).show();
                hideLoading();
            }
        }, mer);

    }



    private void initEvent() {

        billTemporaryFragmentAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MerFragment.this.getActivity(), AddMerActivity.class);
                startActivity(intent);
            }
        });



    }



    // 更新下拉列表
    private void updateListView(String searchText, List<String> searchData) {
        List<String> filteredData = new ArrayList<>();
        for (String data : searchData) {
            if (data.toLowerCase().contains(searchText.toLowerCase())) {
                filteredData.add(data);
            }
        }

        // 清空原有列表项
        linearListView.removeAllViews();

        // 动态添加列表项
        for (final String item : filteredData) {
            TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, null);
            textView.setText(item);

            // 添加点击事件
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 处理点击事件，例如跳转到详情页面
                    // 在这里你可以根据需要执行相应的操作
                    // 这里只是简单的示例，你可以根据需求进行修改
                    autoCompleteTextView.setText(item);
                    scrollView.setVisibility(View.GONE);
                }
            });

            linearListView.addView(textView);
        }

        // 显示或隐藏下拉列表
        scrollView.setVisibility(filteredData.isEmpty() ? View.GONE : View.VISIBLE);
    }

    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        if (getActivity() != null) {
            getActivity().getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
        if (getActivity() != null) {
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        }
    }

    public void refreshData() {
        refreshMerchandiseList();
        // 完成刷新后停止 SwipeRefreshLayout 的刷新动画
        swipeRefreshLayout.setRefreshing(false);
    }
}